const $ = layui.$;
export default class Login{
    constructor(){
        this.render();
        this.handle();
    }
    render(){
        let template = `
        <style>
            html,body{
                height:100%;
            }
            body{
                background-color: #c2c2c2;
                display: flex;
                align-items: center;
            }
            .card{
                width:500px;
                margin:auto;
            }
            .card .header{
                text-align: center;
                font-size: 2em;
            }
        </style>
        <div class="layui-card card">
        <div class="layui-card-header header">登录</div>
        <div class="layui-card-body">
          <form class="layui-form" >
            <div class="layui-form-item">
              <label class="layui-form-label">用户名</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  name="username"
                  required
                  lay-verify="required|username"
                  placeholder="请输入用户名"
                  autocomplete="off"
                  class="layui-input"
                />
              </div>
            </div>
            <div class="layui-form-item">
              <label class="layui-form-label">密码</label>
              <div class="layui-input-block">
                <input
                  type="password"
                  name="pwd"
                  required
                  lay-verify="required|pwd"
                  placeholder="请输入密码"
                  autocomplete="off"
                  class="layui-input"
                />
              </div>
            </div>
           
            <div class="layui-form-item">
              <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="loginForm">
                  立即提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary">
                  重置
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
        `;
        $("#root").html(template);
    }
    handle(){
        let form = layui.form;
        form.on('submit(loginForm)',function(data){
          console.log(data);
          $.ajax({
            type:"post",
            url:"/api/users/login",
            data:data.field,
            success(res){
              if(Object.keys(res).length > 0){
                  window.location = "#manage"
                  // 将返回token信息保存在localStorage
                  layui.data('tokens', {
                    key: 'token'
                    ,value: res.token
                  });
                  alert('登录成功');
              }else{
                alert('登录失败');
              }
            }
          });
          return false;
        });
    }
}